package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.mapper.EmployeeMapper;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void delete(Long id) {

        employeeMapper.deleteByPrimaryKey(id);

        // 删除关系
        employeeMapper.deleteRelation(id);
    }

    @Override
    public void save(Employee employee, Long[] ids) {
        // md5 加密（用户名作为盐）
        String name = employee.getName();
        String password = employee.getPassword();
        Md5Hash md5Hash = new Md5Hash(password, name);
        employee.setPassword(md5Hash.toString());

        employeeMapper.insert(employee);

        // 处理中间表关系
        if(ids != null && ids.length > 0){
            for (Long rid : ids) {
                employeeMapper.insertRelation(employee.getId(),rid);
            }
        }
    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public void update(Employee employee, Long[] ids) {

        employeeMapper.updateByPrimaryKey(employee);

        // 删除关系
        employeeMapper.deleteRelation(employee.getId());

        // 处理中间表关系
        if(ids != null && ids.length > 0){
            for (Long rid : ids) {
                employeeMapper.insertRelation(employee.getId(),rid);
            }
        }
    }

    @Override
    public Employee login(String username, String password) {
        Employee employee = employeeMapper.selectByUsernameAndPassword(username, password);
        // 判断用户是否存在
        if(employee == null){
            throw new RuntimeException("账号和密码不存在");
        }

        return employee;

    }

    @Override
    public PageInfo query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        // 查询结果集
        List<Employee> list = employeeMapper.selectForList(qo);
        return new PageInfo(list);

    }

    @Override
    public void batchDelete(Long[] ids) {
        employeeMapper.batchDelete(ids);
    }

    @Override
    public Employee selectByUsername(String username) {
        return employeeMapper.selectByUsername(username);
    }

    // 导出
    @Override
    public Workbook exportXls() {
        // 创建Excel
        Workbook wb = new HSSFWorkbook();
        // 创建一页纸（sheet）
        Sheet sheet = wb.createSheet("员工名单");
        //  标题行
        Row row = sheet.createRow(0);
        // 设置内容到单元格中
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");

        // 查询员工的数据，并设置到每个单元格中
        List<Employee> employees = employeeMapper.selectAll();
        for (int i = 0; i < employees.size(); i++) {
            // 获取每一行的数据
            Employee employee = employees.get(i);
            // 创建行
            row = sheet.createRow(i+1);
            // 设置内容到单元格中
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());
        }
        return wb;
    }

    @Override
    public void importXls(MultipartFile file) throws IOException {
        // 把接收到的文件以 Excel 的方式去读取并操作
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        // 读取第一页
        Sheet sheet = wb.getSheetAt(0);
        // 获取总行数(最大索引数)
        int num = sheet.getLastRowNum();
        // 从索引为1的行数开始读（忽略标题行）
        for (int i = 1; i <= num; i++) {
            // 获取 行数据
            Row row = sheet.getRow(i);
            // excel文本格式
            Employee employee = new Employee();
            employee.setName(row.getCell(0).getStringCellValue());
            employee.setEmail(row.getCell(1).getStringCellValue());
            /*String age = row.getCell(2).getStringCellValue();
            if(!("".equals(age))) {
                employee.setAge(Integer.valueOf(age));
            }*/
            // 若是数值格式的，里面不能为空的内容：
            double age = row.getCell(2).getNumericCellValue();
            employee.setAge((int)age);
            // 设置默认密码 1
            employee.setPassword("1");
            this.save(employee,null);
        }
    }

    @Override
    public List<Employee> selectByRoleSn(String... sns) {
        return employeeMapper.selectByRoleSn(sns);
    }


}
